#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/16 0016 21:17
# @Author  : Arliki
# @File    : answer.py
import subprocess
import requests
import os
import random
from io import BytesIO
from PIL import Image
from aip import AipOcr

config = {
    'title': (80, 500, 1000, 880),
    'answers': (80, 960, 1000, 1720),
    'point': [
        (316, 993, 723, 1078),
        (316, 1174, 723, 1292),
        (316, 1366, 723, 1469),
        (316, 1570, 723, 1657),
    ]
}


def baidu(pw, answers):
    url = 'https://www.baidu.com/s'
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
    }
    data = {
        'wd': pw
    }
    get_all = requests.get(url, params=data, headers=header)
    get_all.encoding = 'utf-8'
    html = get_all.text
    for i in range(len(answers)):
        answers[i] = (html.count(answers[i]), answers[i], i)
    answers.sort(reverse=True)
    return answers[0][2]

def get_screenshot():
    process = subprocess.Popen("adb shell screencap -p", shell=True, stdout=subprocess.PIPE)
    screenshot = process.stdout.read()
    screenshot = screenshot.replace(b'\r\r\n', b'\n')
    # with open('ans.png', 'wb') as f:
    #     f.write(screenshot)
    img_io = BytesIO()
    img_io.write(screenshot)
    img = Image.open(img_io)
    # 题目
    title_img = img.crop(config['title'])
    answer_img = img.crop(config['answers'])
    new_img = Image.new('RGBA', (920, 1140))
    # 拼接
    new_img.paste(title_img, (0, 0, 920, 380))
    new_img.paste(answer_img, (0, 380, 920, 1140))

    new_img_fb = BytesIO()
    new_img.save(new_img_fb, 'png')
    # with open('asw.png','wb') as f:
    #     new_img.save(f)
    return new_img_fb

def get_words_by_img(img):
    APP_ID = '10703069'
    API_KEY = 'LHAPjhbGzGiyo3ooDEsC6LMx'
    SECRET_KEY = 'uidx7NiinXNxpu5yx7AgC1XtGNfr3qG6 '
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    return client.basicGeneral(img)


def get_point(point):
    # 毫秒
    cmd = 'adb shell input swipe %s %s %s %s %s' % (
        point[0],
        point[1],
        point[0] + random.randint(0, 3),
        point[1] + random.randint(0, 3),
        200
    )
    os.system(cmd)

def run():
    while True:
        input("回车开始答题")
        img = get_screenshot()
        info = get_words_by_img(img.getvalue())
        if info['words_result_num'] < 5:
            continue
        answers = [x['words'] for x in info['words_result'][-4:]]
        pw = str(''.join(x['words'] for x in info['words_result'][:-4]))
        print(answers)
        print(pw)
        num = baidu(pw, answers)
        get_point(config['point'][num])

if __name__ == '__main__':
    run()